package com.movies.main;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellUtil;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chemeng on 2017/3/17.
 */
public class Test {

    private static CellStyle cellStyle = null;

    public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException {
        //System.out.print(" name=".matches("^\\s*[a-z]*=\\s*$"));
        //html2Json();
        // poiTest();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
       // calendar.set(Calendar.DAY_OF_MONTH, 1);
        System.out.println(calendar.getTime());
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        System.out.println(calendar.getTime());
        String format = DateFormatUtils.format(calendar, "yyyy-MM");
        System.out.println(format);
        System.out.println(calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
    }

    private static void poiTest() throws IOException {
        FileOutputStream fos = new FileOutputStream("E:\\test.xls");
        HSSFWorkbook workbook = new HSSFWorkbook();

        intiWorkbook(workbook);

        /*CellRangeAddress cra = new CellRangeAddress(0, 3, 0, 6);

        setRangeStyle(cra, sheet, getCellStyle(workbook));
        sheet.addMergedRegion(cra);

        Row row = CellUtil.getRow(0, sheet);
        // 将合并的单元格在开头的单元格上插入数据
        Cell cell_1 = CellUtil.getCell(row, 0);

        cell_1.setCellValue("When you're right , no one remembers, when you're wrong ,no one forgets .");*/


        // 0-6合并了，只能在0上插入数据
        // Cell cell_2 = row.createCell(6);
        //cell_2.setCellValue("what's up ! ");

        // 7是一个堵路的单元格
        //Cell cell_3 = row.createCell(7);
        //cell_3.setCellValue("what's up ! ");
        //cell_3.setCellStyle(cellStyle);
        workbook.write(fos);

        fos.close();


    }

    private static void intiWorkbook(HSSFWorkbook workbook) {
        Sheet sheet = workbook.createSheet("费用结算报表");

        sheet.setDefaultColumnWidth(20);
        sheet.setDefaultRowHeightInPoints(20);

        List<TableHeader> headers = init();

        for (TableHeader header : headers) {
            CellRangeAddress cellRangeAddress = header.getCellRangeAddress();
            setRangeStyle(cellRangeAddress, sheet, getCellStyle(workbook));
            if (cellRangeAddress.getNumberOfCells() >= 2) {
                sheet.addMergedRegion(cellRangeAddress);
            }

            Row row = CellUtil.getRow(cellRangeAddress.getFirstRow(), sheet);
            Cell cell = CellUtil.getCell(row, cellRangeAddress.getFirstColumn());

            cell.setCellValue(header.getHeader());

        }
    }

    private static List<TableHeader> init() {
        List<TableHeader> header = new ArrayList<TableHeader>();
        header.add(new TableHeader("美车师姓名", 0, 1, 0, 0));
        header.add(new TableHeader("服务种类", 0, 1, 1, 1));
        header.add(new TableHeader("服务费用", 0, 0, 2, 3));
        header.add(new TableHeader("城市费用", 1, 1, 2, 2));
        header.add(new TableHeader("员工费用", 1, 1, 3, 3));
        return header;
    }

    private static CellStyle getCellStyle(HSSFWorkbook workbook) {
        if (null != cellStyle) {
            return cellStyle;
        }

        cellStyle = workbook.createCellStyle();

        // 居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 边框
        cellStyle.setBorderTop(BorderStyle.THIN);
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);

        // 字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.BLACK.index);
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 16);

        cellStyle.setFont(font);//选择需要用到的字体格式
        return cellStyle;
    }

    private static void setRangeStyle(CellRangeAddress cra, Sheet sheet, CellStyle cellStyle) {
        for (int rowNum = cra.getFirstRow(); rowNum <= cra.getLastRow(); rowNum++) {
            Row row = CellUtil.getRow(rowNum, sheet);

            for (int column = cra.getFirstColumn(); column <= cra.getLastColumn(); column++) {
                Cell cell = CellUtil.getCell(row, column);

                cell.setCellStyle(cellStyle);
            }
        }
    }

    public static void dataFormat() {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss:SSS");
        StringBuilder sb = new StringBuilder();
        sb.append(dateFormat.format(date));
        System.out.print(sb.toString());
    }

    public static void html2Json() throws ParserConfigurationException, IOException, SAXException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        DocumentBuilder db = dbf.newDocumentBuilder();
        String docFile = "<html><head><meta http-equiv=\"Content-Type\" " +
                "content=\"text/html; charset=UTF-8\"/></head><body><form id = \"pay_form\" " +
                "name= \"pay_form\" action=\"https://gateway.95516.com/gateway/api/frontTransReq.do\" method=\"post\"><input type=\"hidden\" name=\"txnType\" id=\"txnType\" value=\"79\"/><input type=\"hidden\" name=\"frontUrl\" id=\"frontUrl\" value=\"http://test.huijiacn.com/exchange/rest/fastpay/rewind?target_url=lejia://result?success\"/><input type=\"hidden\" name=\"channelType\" id=\"channelType\" value=\"07\"/><input type=\"hidden\" name=\"merId\" id=\"merId\" value=\"898320175420111\"/><input type=\"hidden\" name=\"tokenPayData\" id=\"tokenPayData\" value=\"{trId=62000000349&tokenType=01}\"/><input type=\"hidden\" name=\"txnSubType\" id=\"txnSubType\" value=\"00\"/><input type=\"hidden\" name=\"version\" id=\"version\" value=\"5.0.0\"/><input type=\"hidden\" name=\"accType\" id=\"accType\" value=\"01\"/><input type=\"hidden\" name=\"accNo\" id=\"accNo\" value=\"oSi/AqqcoWqU3ELSaTr9OOuWgp5QgKKf7VGhIJ1TvGbTlo5rnFP4xxYndQbQx9+R/L2YHy4VtRNRlHkuoDnd6V9kxNOi1c8sZ0K7dz0X8L4fiTnK1oZ4x0MSpR0C5tUHV/TNUAxhNxbWspkbOQEhSW+dncdcfHwgIGoJzj09r/C8kaMQQ4yfhJaONmG8MifxZorE2ZlpxEsrwceo0eQ5SFc/VMXa/KwqAdayr/j/gbT2LlPrfR2zxlWGjhYPZJR1rlnV6VMV3u1S0ilHyOc6U6pWjDKVbadpTReQCdcdoG5qjtNXW4uATLxpIOiG64ned49ggch0q3YcGh0PCbJn5w==\"/><input type=\"hidden\" name=\"signMethod\" id=\"signMethod\" value=\"01\"/><input type=\"hidden\" name=\"backUrl\" id=\"backUrl\" value=\"http://test.huijiacn.com/exchange/rest/acpUnion/receiveStatus\"/><input type=\"hidden\" name=\"certId\" id=\"certId\" value=\"70380696422\"/><input type=\"hidden\" name=\"encoding\" id=\"encoding\" value=\"UTF-8\"/><input type=\"hidden\" name=\"bizType\" id=\"bizType\" value=\"000902\"/><input type=\"hidden\" name=\"encryptCertId\" id=\"encryptCertId\" value=\"69042905377\"/><input type=\"hidden\" name=\"signature\" id=\"signature\" value=\"G3ulaZfXsltdipSkw+I5saXiMIMER9tjOSSyuRDzLB/vAJETLJwj4DcQRnGuvqn4HVx9eEt8Nn9FozxGelpcqRBYpYVNHISnliBT5gfZXb7P5g2CT5sSa716TmTbDqDrMzLaUizYOsGQZbcYQFOBh6DfBB/j4au5rKjKmVCh2jUsa/Tn6nUkrcbTKit/EOMtG1X/SsRV3tb6RzwoaUWd1wZ/5QzfbwplTjLwrheSdte8Q2ieyt8ISk+mj0RLzD1DLwYdmwDu9kEVGFSYIP246qcWAizhNcXBh0g/s+0SQSE10FbaFtubozzRaZ7z5j6O0xBBCtrjMUwOBP5bTgGV2w==\"/><input type=\"hidden\" name=\"orderId\" id=\"orderId\" value=\"20170322161151986677\"/><input type=\"hidden\" name=\"txnTime\" id=\"txnTime\" value=\"20170322161151\"/><input type=\"hidden\" name=\"accessType\" id=\"accessType\" value=\"0\"/></form></body><script type=\"text/javascript\">document.forms['pay_form'].submit();</script></html>";
        String a = getEscapedStr(docFile);
        ByteArrayInputStream stream = new ByteArrayInputStream(a.getBytes("UTF-8"));
        Document doc = db.parse(stream);

        Map<String, String> result = new HashMap<String, String>();

        NodeList inputList = doc.getElementsByTagName("input");
        for (int i = 0; i < inputList.getLength(); i++) {
            Node input = inputList.item(i);
            NamedNodeMap attributes = input.getAttributes();
            Node name = attributes.getNamedItem("name");
            result.put("name", name.getNodeValue());
            Node value = attributes.getNamedItem("value");
            result.put("value", value.getNodeValue());
        }

    }


    private static String getEscapedStr(String str) {
        StringBuilder result = new StringBuilder();

        String[] stray = str.split("\"");
        for (int i = 0; i < stray.length; i++) {
            if (stray[i].matches("^\\s*[a-z]*=\\s*$")) {
                stray[i + 1] = StringEscapeUtils.escapeXml(stray[i + 1]);
            }
        }
        result.append(stray[0]);
        for (int i = 1; i < stray.length; i++) {//组合字符串
            result.append("\"");
            result.append(stray[i]);
        }

        return result.toString();
    }


}
